<template>
    <div class="building-tree-elevator-inside">
        <building-org-tree :loading="loading" :data="data" :menu-list="buildingTreeMenuList"
            @onPopoverShow="onBuildingTreePopoverShow" @onMenuClick="onBuildingTreeMenuClick">
        </building-org-tree>

        <el-dialog v-model="buildingDialogShow" width="300px" :title="currentOperateMenuItem.name"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form ref="buildingFormRef" :model="buildingForm" :rules="buildingFormRules" label-position="top" inline>
                <el-form-item label="楼栋名称" prop="name">
                    <el-input v-model="buildingForm.name" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="switchBuildingDialog"> 取消 </el-button>
                    <el-button type="primary" :loading="dialogBtnLoading"
                        @click="currentOperateMenuItem.command === 'addBuilding' ? addBuilding() : updateBuildingName()">
                        <span>确认</span>
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="unitDialogShow" width="300px" :title="currentOperateMenuItem.name" :close-on-click-modal="false"
            :close-on-press-escape="false">
            <el-form ref="unitFormRef" :model="unitForm" :rules="unitFormRules" label-position="top" inline>
                <el-form-item label="单元名称" prop="name">
                    <el-input v-model="unitForm.name" placeholder="请输入" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="switchUnitDialog"> 取消
                    </el-button>
                    <el-button type="primary" :loading="dialogBtnLoading"
                        @click="currentOperateMenuItem.command === 'addUnit' ? addUnit() : updateUnitName()">
                        <span>确认</span>
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="elevatorDialogShow" width="300px" :title="currentOperateMenuItem.name"
            :close-on-click-modal="false" :close-on-press-escape="false">
            <el-form ref="elevatorFormRef" :model="elevatorForm" :rules="elevatorFormRules" label-position="top" inline>
                <el-form-item label="电梯编码" prop="eleNum">
                    <el-input v-model="elevatorForm.eleNum" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="电梯名称" prop="name">
                    <el-input v-model="elevatorForm.name" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="电梯类型" prop="eleType">
                    <el-select v-model="elevatorForm.eleType" placeholder="请选择">
                        <el-option v-for="(elevatorType, index) in elevatorTypeList" :key="index" :label="elevatorType.name"
                            :value="elevatorType.code">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div>
                    <el-button @click="switchElevatorDialog"> 取消
                    </el-button>
                    <el-button type="primary" :loading="dialogBtnLoading"
                        @click="currentOperateMenuItem.command === 'addElevator' ? addElevator() : updateElevator()">
                        <span>确认</span>
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <point-drawer :id="buildingTreeCurrentNodeData.id" v-model:is-point-drawer-show="pointDrawerShow" point-type="inner"
            @onAddPointConfirm="emit('onDataChange')">
        </point-drawer>
        <edit-point-drawer point-type="inner" :id="buildingTreeCurrentNodeData.id"
            v-model:is-edit-point-drawer-show="editPointDrawerShow" :sign-type="buildingTreeCurrentNodeData.signType"
            @onEditPointConfirm="emit('onDataChange')">
        </edit-point-drawer>
    </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, ComponentInternalInstance, getCurrentInstance } from 'vue';
import { useStore } from 'vuex';
import BuildingOrgTree from '@/components/buildingOrgTree/Index.vue';
import PointDrawer from '@/views/resource/houseManage/components/Point.vue';
import EditPointDrawer from '@/views/resource/houseManage/components/EditPoint.vue';
import resourceApi from '@/api/resource';
import { BuildingTreeElevatorInsideState, BuildingTreeData, BuildingTreeMenuItem } from './buildingTreeType';

const props = defineProps({
    loading: {
        type: Boolean,
        default: false,
    },
    data: {
        type: Object,
        default: () => {
            return {};
        },
    },
});
const emit = defineEmits(['onDataChange']);

const store = useStore();
const elevatorTypeList = store.state.app.common.CommonList.elevatorList;
const currentInstance = <ComponentInternalInstance>getCurrentInstance();
const state = reactive<BuildingTreeElevatorInsideState>({
    buildingTreeData: {
        id: '',
        pid: '',
        level: 1,
        name: '',
        premisesId: '',
        buildId: '',
        signType: 1,
        eleType: '',
        gateType: '',
        subType: '',
        showEdit: false,
        showDelete: false,
        sonList: [],
        expand: true,
    },
    buildingTreeMenuList: [],
    buildingTreePopoverShow: false,
    buildingTreeCurrentNodeData: {
        id: '',
        pid: '',
        level: 1,
        name: '',
        premisesId: '',
        buildId: '',
        signType: 1,
        eleType: '',
        gateType: '',
        subType: '',
        showEdit: false,
        showDelete: false,
        sonList: [],
        expand: true,
    },
    currentOperateMenuItem: {
        command: '',
        name: '',
        show: true,
    },
    dialogBtnLoading: false,
    buildingDialogShow: false,
    buildingForm: {
        name: '',
    },
    buildingFormRules: {
        name: [{ required: true, message: '请输入楼盘名称', trigger: 'blur' }],
    },
    unitDialogShow: false,
    unitForm: {
        name: '',
    },
    unitFormRules: {
        name: [{ required: true, message: '请输入单元名称', trigger: 'blur' }],
    },
    elevatorDialogShow: false,
    elevatorForm: {
        eleNum: '',
        name: '',
        eleType: '',
    },
    elevatorFormRules: {
        eleNum: [{ required: true, message: '请输入电梯编码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                const reg = /^[0-9a-zA-Z-]{1,}$/;
                // if (/[/\\:*"<>| ?？》《：“”、\s]/gi.test(value)) {
                if (!reg.test(value)) {
                    // eslint-disable-next-line no-useless-escape
                    callback(new Error('只支持字母数字或 - '));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
        ],
        name: [{ required: true, message: '请输入电梯名称', trigger: 'blur' }],
        eleType: [{ required: true, message: '请选择电梯类型', trigger: 'blur' }],
    },
    pointDrawerShow: false,
    editPointDrawerShow: false,
});
const {
    buildingTreeData,
    buildingTreeMenuList,
    buildingTreePopoverShow,
    buildingTreeCurrentNodeData,
    currentOperateMenuItem,
    dialogBtnLoading,
    buildingDialogShow,
    buildingForm,
    buildingFormRules,
    unitDialogShow,
    unitForm,
    unitFormRules,
    elevatorDialogShow,
    elevatorForm,
    elevatorFormRules,
    pointDrawerShow,
    editPointDrawerShow,
} = toRefs(state);

const onBuildingTreePopoverShow = (currentNodeData: BuildingTreeData) => {
    state.buildingTreeCurrentNodeData = currentNodeData;
    setBuildingTreeMenu();
};
const setBuildingTreeMenu = () => {
    if (state.buildingTreeCurrentNodeData.level === 1) {
        state.buildingTreeMenuList = [
            {
                command: 'addBuilding',
                name: '新建楼栋',
                show: true,
            },
        ];
    }
    if (state.buildingTreeCurrentNodeData.level === 2) {
        state.buildingTreeMenuList = [
            {
                command: 'editBuilding',
                name: '编辑楼栋',
                show: state.buildingTreeCurrentNodeData.showEdit,
            },
            {
                command: 'addUnit',
                name: '新建单元',
                show: true,
            },
            {
                command: 'deleteBuilding',
                name: '删除',
                show: state.buildingTreeCurrentNodeData.showDelete,
            },
        ];
    }
    if (state.buildingTreeCurrentNodeData.level === 3) {
        state.buildingTreeMenuList = [
            {
                command: 'editUnit',
                name: '编辑单元',
                show: state.buildingTreeCurrentNodeData.showEdit,
            },
            {
                command: 'addElevator',
                name: '新建电梯',
                show: true,
            },
            {
                command: 'deleteUnit',
                name: '删除',
                show: state.buildingTreeCurrentNodeData.showDelete,
            },
        ];
    }
    if (state.buildingTreeCurrentNodeData.level === 4) {
        state.buildingTreeMenuList = [
            {
                command: 'editElevator',
                name: '编辑电梯',
                show: state.buildingTreeCurrentNodeData.showEdit,
            },
            {
                command: 'managePoint',
                name: '管理点位',
                show: true,
            },
            {
                command: 'deleteElevator',
                name: '删除',
                show: state.buildingTreeCurrentNodeData.showDelete,
            },
        ];
    }
    if (state.buildingTreeCurrentNodeData.level === 5) {
        state.buildingTreeMenuList = [
            {
                command: 'editPoint',
                name: '编辑点位',
                show: true,
            },
        ];
    }
};
const onBuildingTreeMenuClick = (menuItem: BuildingTreeMenuItem) => {
    console.log('menuItem', menuItem);
    state.currentOperateMenuItem = menuItem;
    switch (menuItem.command) {
        // 新建楼栋
        case 'addBuilding':
            switchBuildingDialog();
            break;
        // 编辑楼栋
        case 'editBuilding':
            state.buildingForm.name = state.buildingTreeCurrentNodeData.name;
            switchBuildingDialog();
            break;
        // 删除楼栋
        case 'deleteBuilding':
            deleteBuilding();
            break;
        // 新建单元
        case 'addUnit':
            switchUnitDialog();
            break;
        // 编辑单元
        case 'editUnit':
            state.unitForm.name = state.buildingTreeCurrentNodeData.name;
            switchUnitDialog();
            break;
        // 删除单元
        case 'deleteUnit':
            deleteUnit();
            break;
        // 新建电梯
        case 'addElevator':
            state.elevatorForm.eleNum = '';
            state.elevatorForm.name = '';
            state.elevatorForm.eleType = '';
            switchElevatorDialog();
            break;
        // 编辑电梯
        case 'editElevator':
            state.elevatorForm.eleNum = state.buildingTreeCurrentNodeData.eleNum;
            let name = '';
            const nameStartIndex = state.buildingTreeCurrentNodeData.name.indexOf('(');
            const nameEndIndex = state.buildingTreeCurrentNodeData.name.indexOf(')');
            if (nameStartIndex >= 0 && nameEndIndex >= 0) {
                name = state.buildingTreeCurrentNodeData.name.slice(nameStartIndex + 1, nameEndIndex)
            }
            state.elevatorForm.name = name;
            state.elevatorForm.eleType = state.buildingTreeCurrentNodeData.eleType;
            switchElevatorDialog();
            break;
        // 管理点位
        case 'managePoint':
            switchPointDrawer();
            break;
        // 删除电梯
        case 'deleteElevator':
            deleteElevator();
            break;
        // 编辑点位
        case 'editPoint':
            switchEditPointDrawer();
            break;
    }
};

// 开关楼栋Dialog
const switchBuildingDialog = () => {
    state.buildingDialogShow = !state.buildingDialogShow;
    if (!state.buildingDialogShow) {
        currentInstance.refs['buildingFormRef'].resetFields();
    }
};
// 开关单元Dialog
const switchUnitDialog = () => {
    state.unitDialogShow = !state.unitDialogShow;
    if (!state.unitDialogShow) {
        currentInstance.refs['unitFormRef'].resetFields();
    }
};
// 开关电梯Dialog
const switchElevatorDialog = () => {
    state.elevatorDialogShow = !state.elevatorDialogShow;
    if (!state.elevatorDialogShow) {
        currentInstance.refs['elevatorFormRef'].resetFields();
    }
};
function reserElevatorForm() {
    state.elevatorDialogShow = false;
    currentInstance.refs['elevatorFormRef'].resetFields();
}
// 开关管理点位Drawer
const switchPointDrawer = () => {
    state.pointDrawerShow = !state.pointDrawerShow;
};
// 开关编辑点位Drawer
const switchEditPointDrawer = () => {
    state.editPointDrawerShow = !state.editPointDrawerShow;
};

// 新建楼栋
const addBuilding = () => {
    currentInstance.refs['buildingFormRef'].validate(async (valid: boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                const params = {
                    premisesId: state.buildingTreeCurrentNodeData.id,
                    name: state.buildingForm.name,
                };
                await resourceApi.addBuilding(params);
                currentInstance?.appContext.config.globalProperties.$message.success('新建成功');
                switchBuildingDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 修改楼栋名称
const updateBuildingName = async () => {
    currentInstance.refs['buildingFormRef'].validate(async (valid: boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                const params = {
                    buildId: state.buildingTreeCurrentNodeData.id,
                    name: state.buildingForm.name,
                };
                await resourceApi.updateBuildingName(params);
                currentInstance?.appContext.config.globalProperties.$message.success('编辑成功');
                switchBuildingDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 删除楼栋
const deleteBuilding = async () => {
    try {
        const params = {
            buildId: state.buildingTreeCurrentNodeData.id,
        };
        await resourceApi.deleteBuilding(params);
        currentInstance?.appContext.config.globalProperties.$message.success('删除成功');
        emit('onDataChange');
    } finally {
    }
};

// 新建单元
const addUnit = () => {
    currentInstance.refs['unitFormRef'].validate(async (valid: boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                const params = {
                    premisesId: state.buildingTreeCurrentNodeData.premisesId,
                    buildId: state.buildingTreeCurrentNodeData.id,
                    name: state.unitForm.name,
                };
                await resourceApi.addUnit(params);
                currentInstance?.appContext.config.globalProperties.$message.success('新建成功');
                switchUnitDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 修改单元名称
const updateUnitName = async () => {
    currentInstance.refs['unitFormRef'].validate(async (valid: boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                const params = {
                    unitId: state.buildingTreeCurrentNodeData.id,
                    name: state.unitForm.name,
                };
                await resourceApi.updateUnitName(params);
                currentInstance?.appContext.config.globalProperties.$message.success('编辑成功');
                switchUnitDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 删除单元
const deleteUnit = async () => {
    try {
        const params = {
            unitId: state.buildingTreeCurrentNodeData.id,
        };
        await resourceApi.deleteUnit(params);
        currentInstance?.appContext.config.globalProperties.$message.success('删除成功');
        emit('onDataChange');
    } finally {
    }
};

// 新建电梯
const addElevator = () => {
    currentInstance.refs['elevatorFormRef'].validate(async (valid: boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                const params = {
                    premisesId: state.buildingTreeCurrentNodeData.premisesId,
                    buildId: state.buildingTreeCurrentNodeData.buildId,
                    unitId: state.buildingTreeCurrentNodeData.id,
                    ...state.elevatorForm,
                };
                await resourceApi.addElevator(params);
                currentInstance?.appContext.config.globalProperties.$message.success('新建成功');
                switchElevatorDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 修改电梯
const updateElevator = async () => {
    currentInstance.refs['elevatorFormRef'].validate(async (valid: boolean) => {
        if (valid) {
            state.dialogBtnLoading = true;
            try {
                const params = {
                    elevatorId: state.buildingTreeCurrentNodeData.id,
                    ...state.elevatorForm,
                };
                console.log('params', params);
                await resourceApi.updateElevator(params);
                currentInstance?.appContext.config.globalProperties.$message.success('编辑成功');
                switchElevatorDialog();
                emit('onDataChange');
            } finally {
                state.dialogBtnLoading = false;
            }
        }
    });
};
// 删除电梯
const deleteElevator = async () => {
    try {
        const params = {
            elevatorId: state.buildingTreeCurrentNodeData.id,
        };
        await resourceApi.deleteElevator(params);
        currentInstance?.appContext.config.globalProperties.$message.success('删除成功');
        emit('onDataChange');
    } finally {
    }
};
</script>

<style lang="scss" scoped>
.building-tree-elevator-inside {
    height: 100%;
}
</style>
